package com.wrupple.muba.common.client.activity;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.Image;
import com.wrupple.muba.common.client.state.GridSelectionState.GridPlaceSelectionStateDelegate;
import com.wrupple.muba.common.client.state.IconSelectionTask;
import com.wrupple.muba.common.client.state.IconSelectionTask.GridElement;
import com.wrupple.muba.common.domain.DesktopPlace;
import com.wrupple.muba.common.shared.StateTransition;
import com.wrupple.muba.widget.client.widgets.GridElementImpl;
import com.wrupple.muba.widget.client.widgets.panels.LayoutGrid;

public class IconWithLabelPlaceDelegate<T extends DesktopPlace> implements
		GridPlaceSelectionStateDelegate<T> {

	class SelectionClickHandler implements ClickHandler {
		T o;
		StateTransition<List<T>> onDone;

		protected SelectionClickHandler(T o, StateTransition<List<T>> onDone) {
			super();
			this.o = o;
			this.onDone = onDone;
		}

		@Override
		public void onClick(ClickEvent event) {
			onDone.setResultAndFinish(Collections.singletonList(o));
		}

	}

	@Override
	public List<GridElement> getElements(List<T> parameter,
			final StateTransition<List<T>> onDone) {
		if (parameter == null) {
			return null;
		}
		List<GridElement> regreso = new ArrayList<IconSelectionTask.GridElement>();
		GridElement e;
		for (T o : parameter) {
			Image image = getImage(o);
			image.addClickHandler(new SelectionClickHandler(o, onDone));
			String label = getLabel(o);
			e = new GridElementImpl(image, label);
			regreso.add(e);
		}
		return regreso;
	}

	@Override
	public LayoutGrid getLayoutGrid() {
		int columns = 4;
		int height = 200;
		int width=200;
		return new LayoutGrid(columns ,height,width);
	}

	@Override
	public int getGridWidth() {
		return 800;
	}

	protected String getLabel(T o) {
		return o.getName();
	}

	protected Image getImage(T o) {
		//FIXME
		String image = "/vegetate/catalog/PersistentFileMetadata/read/"+o.getProperty(DesktopPlace.IMAGE_PARAMETER);
		return new Image(image);
	}
}
